import time


class pipelineTrigger():

    def getTrigger(project):

        # obtain a project triggers description
        triggersList = []
        
        for triggers in project.triggers.list():
            triggersList.append(triggers)

        return triggersList

    def createTrigger(project, triggersDecription):

        # obtain a exist trigger description
        for t in pipelineTrigger.getTrigger(project):
            if triggersDecription in t.description:
                return "trigger already exists"
        # obtain a not exist trigger description
        for t in pipelineTrigger.getTrigger(project):
            if triggersDecription not in t.description:
                createTrigges = project.triggers.create(
                    {'description': triggersDecription})
            return createTrigges

    def runTriggerPipeline(project, triggersDecription):
        # obtain exist description run trigger
        for t in pipelineTrigger.getTrigger(project):
            if triggersDecription in t.description:
                # Trigger a CI build
                # variables is Optional
                triggerPipeline = project.trigger_pipeline('main', t.token, variables={
                    "DEPLOY_ZONE": "us-west1"})
        return triggerPipeline


class pipelineSchedule():
    def getSchedules(project):
        scheds = []
        # list all data for project schedule
        for sched in project.pipelineschedules.list():
            scheds.append(sched)
        return scheds

    def createSchedules(project, scheduledescription):
        # a plan that exist
        for s in pipelineSchedule.getSchedules(project):
            if scheduledescription in s.description:
                return "Scheduled task already exists"

        # crete a plan that don`t exist
        for s in pipelineSchedule.getSchedules(project):
            if scheduledescription not in s.description:
                sched = project.pipelineschedules.create({
                    'ref': 'main',
                    'description': scheduledescription,
                    'cron': '0 2 * * *'
                })
            return sched
